﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace Wattpad
{
    public class IsolatedStorage_Utility
    {
        public static void Save<T>(string fileName, T item)
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(fileStream, item);
                }
            }
        }
        public static T Load<T>(string fileName)
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    return (T)serializer.ReadObject(fileStream);
                }
            }
        }
        public static byte[] ImageToByteArray(BitmapSource bitmapSource)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                WriteableBitmap writableBitmap = new WriteableBitmap(bitmapSource);
                Extensions.SaveJpeg(writableBitmap, stream, bitmapSource.PixelWidth, bitmapSource.PixelHeight, 0, 100);

                return stream.ToArray();
            }
        }
        public static BitmapSource ByteArrayToImage(byte[] bytes)
        {
            BitmapImage bitmapImage = null;
            using (MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length))
            {
                bitmapImage = new BitmapImage();
                bitmapImage.SetSource(stream);
            }

            return bitmapImage;
        }
    }
}
